<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import { useAuth } from '@/stores/index'
import { ElMessage } from 'element-plus'
import APIInformation from '@/api/information'

const dialogVisible = shallowRef(false)
const $props = defineProps<Props>()
const $emit = defineEmits<Emits>()
const { getInfo } = useAuth()

let timer: number | null

watch($props, (newValue) => {
    dialogVisible.value = newValue.modelValue
    if (dialogVisible.value) {
        getBindQRCode()
    }
}, { immediate: true })

watch(dialogVisible, (newValue) => {
    $emit('update:modelValue', newValue)
})

function onBeforeClose() {
    dialogVisible.value = false
    if (!timer) return
    clearTimeout(timer)
    timer = null
}

const reqStr = shallowRef<string>('')

const qrcode = shallowRef<string>('')

function getBindQRCode() {
    APIInformation.getBindQRCode().then(({ data }) => {
        reqStr.value = data.req_str
        qrcode.value = data.qrcode
        checkBindState()
    })
}

function checkBindState() {
    APIInformation.checkBindState(reqStr.value).then(({ data }) => {
        if (data.result == 1) {
            ElMessage.success('绑定成功')
            getInfo()
            onBeforeClose()
        } else {
            timer = setTimeout(() => {
                checkBindState()
            }, 2000)
        }
    })
}



</script>

<template>
    <el-dialog class="edit-username" v-model="dialogVisible" title="修改绑定微信公众号" width="600" destroy-on-close
        :before-close="onBeforeClose" :show-close="false">
        <template #header>
            <DialogClose title="修改绑定微信公众号" @close="onBeforeClose" />
        </template>
        <div class="con">
            <img v-if="qrcode" :src="qrcode" alt="">
        </div>
    </el-dialog>
</template>

<style lang="scss" scoped>
.edit-username {
    .con {
        width: 200px;
        height: 200px;
        background-color: #eeeeee;
        margin: 0 auto;

        img {
            width: 100%;
            height: 100%;
        }
    }
}
</style>
